<template>
  <div>
    <a-spin :spinning="spinning">
      <a-layout>
        <a-layout-sider :width="225" style="border-right: 1px solid #e8e8e8;">
          <div
            class="allApp"
            @click="
              current = [];
              selectedKeys = [];
              params = {};
              form.resetFields();
              getApprovalList(1);
            "
          >
            所有审批类型({{ listNumAll }})
          </div>
          <a-menu style="min-height: 600px;" mode="inline" @openChange="openChange" :openKeys.sync="current" v-model="selectedKeys">
            <a-sub-menu v-for="group in items" :key="group.id" :defaultSelectedKeys="[]" @titleClick="subMenuGroup(group)">
              <span slot="title">
                <a-tooltip>
                  <template slot="title">{{ group.groupName }}({{ group[listNumArr[approvalState - 1]] }})</template>
                  <strong>{{ group.groupName }}({{ group[listNumArr[approvalState - 1]] }})</strong>
                </a-tooltip>
              </span>
              <a-menu-item v-for="item in group.approFlowList" :key="item.id" @click="menuItem(item)">
                <a-tooltip>
                  <template slot="title">{{ item.typeName }}({{ item[listNumArr[approvalState - 1]] }})</template>
                  {{ item.typeName }}({{ item[listNumArr[approvalState - 1]] }})
                </a-tooltip>
              </a-menu-item>
            </a-sub-menu>
          </a-menu>
        </a-layout-sider>
        <a-layout-content>
          <!-- title -->
          <a-row class="approval_title" type="flex" align="middle">
            <a-form :form="form" layout="inline">
              <a-form-item class="mg_r20" label="审批时间" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
                <a-range-picker v-decorator="['gmtCreate']" style="width: 240px;" @change="onChange" />
              </a-form-item>
              <a-form-item v-if="approvalState != 1" class="mg_r20" label="审批类型" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
                <a-select v-decorator="['status']" style="width: 200px; margin-left: 20px;" :allow-clear="true" @change="selectApproval">
                  <a-select-option v-for="i in approvalTypeArr(approvalTabState)" :key="i.value" :value="i.value">{{
                    i.state
                  }}</a-select-option>
                </a-select>
              </a-form-item>
            </a-form>
          </a-row>
          <!-- table -->
          <a-table
            :pagination="pagination"
            :data-source="data"
            :row-key="(record, index) => index"
            style="margin-left: 24px;"
            @change="handleTableChange"
          >
            <a-table-column title="标题" data-index="remark">
              <template slot-scope="text">{{ text ? text : "--" }}</template>
            </a-table-column>
            <a-table-column title="审批类型" :data-index="approvalTabState == '3' ? 'flowName' : 'approName'" />
            <a-table-column title="发起人" v-if="approvalTabState != '3' && approvalTabState != '4'" data-index="userName">
              <template slot-scope="text">{{ text ? text : "--" }}</template>
            </a-table-column>
            <a-table-column :title="approvalTabState == '3' ? '审批总状态' : '当前节点状态'">
              <template slot-scope="record">
                <div>
                  <span
                    class="fw500 dontBack"
                    :style="{
                      background: getApprovalStatusColorBlue(approvalTabState == '3' ? record.status : record.nodeApproverStatu)
                    }"
                  ></span>
                  <!-- 文字 -->
                  <span v-if="approvalTabState != '3'" class="verAlignSuper">
                    {{ getApprovalStatus(approvalTabState == "4" ? record.approStatu : record.nodeApproverStatu) }}
                  </span>
                  <span v-if="approvalTabState == '3'" class="verAlignSuper">
                    {{ getApprovalStatus(record.status) }}
                  </span>
                </div>
              </template>
            </a-table-column>
            <a-table-column title="发起日期" :data-index="approvalTabState == '3' ? 'gmtCreate' : 'approCreate'">
              <template slot-scope="record">{{ formatDateAll(record, "d") }}</template>
            </a-table-column>
            <a-table-column title="操作">
              <template slot-scope="record">
                <a class="primary_color" type="link" @click="statusDetail(record)">详情</a>
              </template>
            </a-table-column>
          </a-table>
        </a-layout-content>
      </a-layout>
    </a-spin>
  </div>
</template>

<script>
import { Approval, ApprovalApi } from "./apiOld";
import { mapState } from "vuex";
import { getApprovalStatus, getApprovalStatusColorBlue, approvalTypeArr } from "./funcs";
export default {
  props: ["approvalTabState"],
  data() {
    return {
      selectedKeys: [], // 二级菜单
      current: [],
      spinning: false,
      listNumArr: ["waitTaskNum", "hasTaskNum", "createByMeNum", "notifierMeNum"],
      pagination: {
        pageNo: 1,
        pageSize: 20,
        pageSizeOptions: ["10", "20", "50", "100"], // 3,4 有
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      },
      params: {
        statous: null,
        apprvId: null,
        creatUserId: null,
        gmtCreateStart: null,
        gmtCreateEnd: null
      },
      listNumAll: 0,
      userApproverId: "", // 审批操作参数
      form: this.$form.createForm(this, { name: "coordinated" }),
      companyId: this.$store.state.hr.companyId,
      data: [],
      approvalType: [],
      items: [],
      itemTypes: []
    };
  },
  computed: {
    ...mapState(["hr"])
  },
  watch: {
    approvalTabState: {
      handler(val, oldval) {
        if (val) {
          this.createdFun(val);
        }
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    openChange(e) {
      this.current = [];
      this.selectedKeys = [];
    },
    getApprovalStatus,
    getApprovalStatusColorBlue,
    approvalTypeArr,
    // 初始加载
    createdFun(val) {
      this.approvalState = val;
      this.form.resetFields();
      this.items = [];
      this.current = [];
      this.selectedKeys = [];
      this.params = {
        status: null,
        approvId: null,
        creatUserId: null,
        gmtCreateStart: null,
        gmtCreateEnd: null
      };
      this.pagination = {
        pageNo: 1,
        pageSize: 20,
        pageSizeOptions: ["10", "20", "50", "100"], // 3,4 有
        showQuickJumper: true,
        showSizeChanger: true,
        total: 0
      };

      this.getApprovalList(); // 获取审批列表
      this.getAllBySite(); // 获取所有审批
    },

    // 查看审批节点
    statusDetail(record) {
      if (this.approvalState === 3) {
        this.$router.push(`/approval/detail/${record.id}/${record.userId}`);
      } else {
        this.$router.push(`/approval/detail/${record.userApproId}/${record.userApproverId}`);
      }
    },

    // 审批组
    subMenuGroup(item) {
      this.params.approvId = null;
      this.itemTypes = item.approFlowList;
      this.params.approvGroupId = item.id;
      this.getApprovalList(1);
    },
    /* menuItem */
    menuItem(item) {
      this.params.approvGroupId = null;
      this.params.approvId = item.id;
      this.getApprovalList(1);
    },

    // 获取所有审批 bysite
    getAllBySite() {
      const listNumArr = this.listNumArr;
      Approval({
        url: ApprovalApi.allByCompanyAndUser + this.companyId + `/hr`
      })
        .then(data => {
          this.items = data.data;
          var listNum = 0;
          this.items.forEach(item => {
            item.key = item.id;
            item.title = item.groupName;
            listNum += item[listNumArr[this.approvalState - 1]];
          });
          this.listNumAll = listNum;
        })
        .catch(err => console.warn(err));
    },

    /* 获取审批列表 */
    getApprovalList(e) {
      const urlArr = ["myApproval", "myApproval", "creFromMe", "ccMe"];
      this.spinning = true;
      if (e) {
        this.pagination.pageNo = 1;
        this.pagination.current = 1;
      }
      Approval({
        url: ApprovalApi[urlArr[this.approvalState - 1]],
        params: {
          ...this.params,
          ...this.pagination,
          companyId: this.companyId,
          moduleType: "hr",
          hasAppro: this.approvalState === 1 ? false : this.approvalState === 2 ? true : null // 是否审批
        }
      }).then(({ data }) => {
        this.spinning = false;
        this.data = data.entities;

        this.pagination.total = data.entityCount;
      });
    },
    handleTableChange(pagination, filters, sorter) {
      this.pagination.pageNo = pagination.current;
      this.getApprovalList();
    },
    // 筛选审批类型
    selectApproval(e) {
      this.params.status = e;
      this.getApprovalList(1);
    },

    /* 日期选择 */
    onChange(date, dateString) {
      this.params.gmtCreateStart = null;
      this.params.gmtCreateEnd = null;
      const CreateStart = `${dateString[0]} 00:00:00`;
      const CreateEnd = `${dateString[0]} 23:59:59`;
      if (date.length) {
        this.params.gmtCreateStart = Date.parse(new Date(CreateStart));
        this.params.gmtCreateEnd = Date.parse(new Date(CreateEnd));
      }
      this.getApprovalList();
    }
  }
};
</script>

<style lang="scss" scoped>
@import "./style/my-approval.scss";
</style>
